﻿
using System.Windows.Controls;
using System.Windows;

namespace QH_MSS_WPF_Core.Extensions
{
    public class ElementHelper : DependencyObject
    {
        public static readonly DependencyProperty IsClearProperty =
          DependencyProperty.RegisterAttached("IsClear", typeof(bool), typeof(ElementHelper),
              new PropertyMetadata(false, OnIsClearChanged));

        public static void SetIsClear(UIElement element, bool value)
        {
            element.SetValue(IsClearProperty, value);
        }

        public static bool GetIsClear(UIElement element)
        {
            return (bool)element.GetValue(IsClearProperty);
        }

        private static void OnIsClearChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var button = d as Button;
            if (button != null)
            {
                if ((bool)e.NewValue)
                    button.Click += ButtonClear_Click;
                else
                    button.Click -= ButtonClear_Click;
            }
        }

        private static void ButtonClear_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button)
            {
                if (button.TemplatedParent is TextBox textBox)
                {
                    textBox.Clear();
                }
            }
        }
    }
}
